/*
 This file is part of BTStracker
		
    BTStracker is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    BTStracker is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Foobar.  If not, see <http://www.gnu.org/licenses/>.	
	author: azbest.pro (azbest.pro@gmail.com)
*/
package pl.vdl.azbest.log.gui.composite;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;

import pl.vdl.azbest.annotations.TODO;
import pl.vdl.azbest.log.LoggingTheGathering;


import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Combo;

@TODO(dateAssigned = "30-03-2008", level = pl.vdl.azbest.annotations.Level.DOCUMENTATION, target = ""
		+ "1.Create logging chooser for classess in project / applcation chengable at runtime<br>"
		+ "2.Create logging handlers to file, to txt area, to console with dnamic choosing <br>"
		+ "3.Add saving settings to separate config file for logging<br>"
		+ "<br>", done = "1. - partialy")
public class CompositeLoggingTheGathering extends Composite {

	private Tree tree = null;

	public CompositeLoggingTheGathering(Composite parent, int style) {
		super(parent, style);
		initialize();
	}
	{
		LoggingTheGathering.addPath(getClass().getName());
	}
	private void initialize() {
		GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 1;
		GridData gridData = new GridData();
		gridData.horizontalAlignment = GridData.FILL;
		gridData.grabExcessHorizontalSpace = true;
		gridData.grabExcessVerticalSpace = true;
		gridData.widthHint = 300;
		gridData.heightHint = -1;
		gridData.verticalAlignment = GridData.FILL;
		tree = new Tree(this, SWT.CHECK | SWT.BORDER);
		tree.setHeaderVisible(true);
		tree.setLayoutData(gridData);
		this.setLayout(gridLayout);
		createGroup();
		tree.addDisposeListener(new org.eclipse.swt.events.DisposeListener() {
			public void widgetDisposed(org.eclipse.swt.events.DisposeEvent e) {
				try {
					saveSelection();
				} catch (IOException E) {
					E.printStackTrace();
				}
				LoggingTheGathering.isLoggerOn= false;

			}
		});
		this.setSize(new Point(494, 232));
		init();
	}

	private void init() {
		label1.setText(""+LoggingTheGathering.getList().size());
		for (String input : LoggingTheGathering.getList()) {
			loadStuff(input);
		}
		
		for (TreeItem item : tree.getItems()) {
			setChecked(item);
		}
		combo.add(Level.ALL.getName());
		combo.add(Level.OFF.getName());
		combo.add(Level.CONFIG.getName());
		combo.add(Level.FINE.getName());
		combo.add(Level.FINER.getName());
		combo.add(Level.FINEST.getName());
		combo.add(Level.INFO.getName());
		combo.add(Level.SEVERE.getName());
		combo.add(Level.WARNING.getName());
		combo.select(0);
		
		
	}

	private void setChecked(TreeItem i) {
		TreeItem[] tx = null;
		System.out.println(i.getText());
		System.out.println((String) i.getData());
		if ((tx = i.getItems()) != null) {
			for (TreeItem i2 : tx) {
				if (listToEnableLogger.contains((String) i2.getData())) {
					i2.setChecked(true);
				}
				setChecked(i2);
			}
		}
	}

	private HashMap<String, TreeItem> map = new HashMap<String, TreeItem>();

	public void loadStuff(String input) {
		StringTokenizer st = new StringTokenizer(input, ".");

		int countt = st.countTokens();
		int i = st.countTokens();
		String lastItemName = "";
		String data = "";

		while (st.hasMoreElements()) {
			String name = (String) st.nextElement();

			System.out.println("name = " + name);
			System.out.println("lastName = " + lastItemName);

			if (map.containsKey(name)) {
				// do nothing - already have it
				lastItemName = name;
				if (i == countt)
					data += name;
				else
					data += "." + name;
			} else {
				if (i == countt) {
					// first item without parent
					TreeItem item = new TreeItem(tree, SWT.NULL);
					item.setText(name);
					map.put(name, item);
					lastItemName = name;
					if (i == countt)
						data += name;
					else
						data += "." + name;
					item.setData(data);
				} else {
					// next item with aparent
					TreeItem item = new TreeItem(map.get(lastItemName),
							SWT.NULL);
					item.setText(name);
					map.put(name, item);
					lastItemName = name;
					data += "." + name;
					item.setData(data);
				}
			}
			i--;
		}
	}

	private void scanForCheckedToLog(TreeItem i) {
		TreeItem[] tx = null;
		System.out.println(i.getText());
		System.out.println((String) i.getData());
		if ((tx = i.getItems()) != null) {
			for (TreeItem i2 : tx) {
				if (i2.getChecked())
					listToEnableLogger.add((String) i2.getData());
				scanForCheckedToLog(i2);
			}
		}
	}

	private void scanForCheckedToLog2(TreeItem i) {
		TreeItem[] tx = null;
		System.out.println(i.getText());
		System.out.println((String) i.getData());
		if ((tx = i.getItems()) != null) {
			for (TreeItem i2 : tx) {
				if (i2.getChecked())
					listToEnableLogger2.add((String) i2.getData());
				scanForCheckedToLog2(i2);
			}
		}
	}

	HashSet<String> listToEnableLogger2 = new HashSet<String>(); // @jve:decl-index=0:

	HashSet<String> listToEnableLogger = new HashSet<String>(); // @jve:decl-index=0:

	private Combo combo = null;

	private Group group = null;

	private Label label = null;

	private Label label1 = null;

	private ToolBar toolBar = null;

	private void refreshTree() {

	}

	public void addPath(String path) {
		loadStuff(path);
		System.out.println(path);

	}

	private void saveSelection() throws IOException {

		File f = new File("Selecion.ob");
		if (f.exists())
			f.delete();
		f.createNewFile();
		FileOutputStream fis = new FileOutputStream(new File("Selecion.ob"));
		ObjectOutputStream oos = new ObjectOutputStream(fis);
		oos.writeObject(this.listToEnableLogger);

	}

	private void loadSelection() throws IOException, ClassNotFoundException {

		File f = new File("Selecion.ob");

		FileInputStream fis = new FileInputStream(new File("Selecion.ob"));
		ObjectInputStream oos = new ObjectInputStream(fis);
		Object o = oos.readObject();
		if (o instanceof HashSet)
			this.listToEnableLogger = (HashSet<String>) o;

	}

	/**
	 * This method initializes combo	
	 *
	 */
	private void createCombo() {
		combo = new Combo(group, SWT.READ_ONLY);
	}

	/**
	 * This method initializes group	
	 *
	 */
	private void createGroup() {
		GridData gridData2 = new GridData();
		gridData2.horizontalAlignment = GridData.FILL;
		gridData2.grabExcessHorizontalSpace = true;
		gridData2.verticalAlignment = GridData.CENTER;
		GridLayout gridLayout1 = new GridLayout();
		gridLayout1.numColumns = 4;
		GridData gridData1 = new GridData();
		gridData1.verticalAlignment = GridData.CENTER;
		gridData1.grabExcessHorizontalSpace = true;
		gridData1.grabExcessVerticalSpace = false;
		gridData1.horizontalAlignment = GridData.FILL;
		group = new Group(this, SWT.NONE);
		createToolBar();
		createCombo();
		group.setLayout(gridLayout1);
		group.setLayoutData(gridData1);
		label = new Label(group, SWT.NONE);
		label.setText("Classes loaded: ");
		label1 = new Label(group, SWT.NONE);
		label1.setText("0");
		label1.setLayoutData(gridData2);
	}

	/**
	 * This method initializes toolBar	
	 *
	 */
	private void createToolBar() {
		toolBar = new ToolBar(group, SWT.NONE);
		ToolItem button = new ToolItem(toolBar, SWT.PUSH);
		button.setText("Set logging level");
		
		button.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() {
			public void widgetSelected(
					org.eclipse.swt.events.SelectionEvent e) {
				listToEnableLogger.clear();
				for (TreeItem item : tree.getItems()) {
					scanForCheckedToLog(item);
				}
				for (String s : listToEnableLogger) {
					System.out.println("setting logger ON for >" + s);
					Logger.getLogger(s).setLevel(Level.parse(combo.getText()));
				}
			}
		});
	}

}  //  @jve:decl-index=0:visual-constraint="39,-41"
